/**
 * author:Administrator
 * date:2016/1/6
 * desc: test account
 *
 * ------account basic curd---------
 * step 1-0: create acc1
 * step 1-1: update acc1
 * step 1-2: read acc1
 * step 1-3: delete acc1
 */
"use strict";

var assert = require('assert');
var request = require('request');
var testUtils = require('./test_utils.js');

var httpPort = require('../config/index.js').http.port;
var __hostPort = 'http://localhost:' + httpPort;
var __acc = {
  name: 'foo',
  money: '99'
};
var __edited = {
  name: 'foo2',
  money: 12.34
};

var stepCreate;
function waitCreateDone(done) {
  if (!!stepCreate)done();
  else setTimeout(function () {
    waitCreateDone(done);
  }, 500);
}

var stepUpdate;
function waitUpdateDone(done) {
  if (!!stepUpdate)done();
  else setTimeout(function () {
    waitCreateDone(done);
  }, 500);
}

var stepRead;
function waitReadDone(done) {
  if (!!stepRead)done();
  else setTimeout(function () {
    waitReadDone(done);
  }, 500);
}

describe('account basic curd', function () {
  it('create', function (done) {
    var url = __hostPort + '/accounts';
    testUtils.postJson(url, __acc, function (err, res, data) {
      assert.equal(!!err, false);
      if (typeof data === 'string') data = JSON.parse(data);
      assert.equal(0, data.errcode);
      __acc.id = data.account.id;
      stepCreate = 1;
      done();
    });
  });
});

describe('account basic curd', function () {
  this.timeout(5000);
  before(function (done) {
    waitCreateDone(done);
  });

  it('update', function (done) {
    var url = __hostPort + '/accounts/' + __acc.id;
    testUtils.putJson(url, __edited, function (err, res, data) {
      assert.equal(!!err, false);
      if (typeof data === 'string') data = JSON.parse(data);
      assert.equal(0, data.errcode);
      stepUpdate = 1;
      done();
    });
  });
});

describe('account basic curd', function () {
  this.timeout(5000);
  before(function (done) {
    waitUpdateDone(done);
  });
  it('read', function (done) {
    var url = __hostPort + '/accounts/' + __acc.id;
    request(url, function (err, res, data) {
      assert.equal(!!err, false);
      if (typeof data === 'string') data = JSON.parse(data);
      assert.equal(0, data.errcode);
      assert.equal(__edited.name, data.account.name);
      assert.equal(__edited.money, data.account.money);
      stepRead = 1;
      done();
    });
  });
});

describe('account basic curd', function () {
  this.timeout(5000);
  before(function (done) {
    waitReadDone(done);
  });
  it('delete', function (done) {
    var url = __hostPort + '/accounts/' + __acc.id;
    testUtils.deleteJson(url, null, function (err, res, data) {
      assert.equal(!!err, false);
      if (typeof data === 'string') data = JSON.parse(data);
      assert.equal(0, data.errcode);
      done();
    });
  });
});